<?php
namespace app\admin\service;

class UploadService extends BaseService
{

    /**
     * 创建目录
     *
     * @param $path
     *
     * @return bool
     */
    function initFileDir($path){
        $temp_path = UPLOAD_PATH;
        if(is_dir(UPLOAD_PATH.$path)){
            return TRUE;
        }
        if(!is_dir(UPLOAD_PATH)){
            mkdir($temp_path,0775);
        }
        $path_arr = explode(DS,$path);

        foreach ($path_arr as $val){
            if(empty($val)){
                continue;
            }
            $temp_path .=  $val . DS;

            if(!is_dir($temp_path)){
                mkdir($temp_path,0775);
            }
        }
        if(is_dir($temp_path)){
            return TRUE;
        }
        return FALSE;
    }

    /**
     * 保存图片（base64格式）
     *
     * @param        $image
     * @param string $file
     *
     * @return int
     */
    function saveUploadBase64Image($image,$file=""){
        if(empty($file)){
            $file = date('Y/m/d/');
        }

        $re = $this->initFileDir($file);
        if(!$re){
            return array(
                'code' => -1,
                'msg' => '没有写入权限'
            );
        }
        if(!preg_match('/^(data:\s*image\/(\w+);base64,)/', $image, $result)){
            return array(
                'code' => -2,
                'msg' => '图像解析失败'
            );
        }
        $type = $result[2];
        $image_name = uuid() . '.' . $type;
        //解码
        $decode=base64_decode(str_replace($result[1], '', $image));
        $re = file_put_contents(UPLOAD_PATH . $file . $image_name,$decode);
        if($re){
            return array(
                'code' => 0,
                'msg' => '上传成功',
                'data' => '/static/upload/'.$file.$image_name
            );
        }
        return array(
            'code' => -3,
            'msg' => '图像保存失败'
        );
    }

    /**
     * 保存图片(文件格式)
     *
     * @param        $image
     * @param string $file
     *
     * @return int
     */
    function saveUploadFileImage($image,$file=""){
        if(empty($file)){
            $file = date('Y/m/d/');
        }

        $re = $this->initFileDir($file);
        if(!$re){
            return array(
                'code' => -1,
                'msg' => '没有写入权限'
            );
        }

        $image = \think\Image::open($image);
        $type = $image->type();
        $image_name = uuid() . '.' . $type;

        $result = $image->save(UPLOAD_PATH . $file . $image_name);
        if(!$result){
            return array(
                'code' => -2,
                'msg' => '图像储存失败'
            );
        }
        return array(
            'code' => 0,
            'msg' => '上传成功',
            'data' => '/static/upload/'.$file.$image_name
        );
    }
}